package com.wy2.springcloud.sample.rest.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Json工具类
 * @author nnsword
 * @date 2018年1月5日下午10:23:17
 *
 */
public final class JsonTools {
    
    private static final Logger logger=LoggerFactory.getLogger(JsonTools.class);
    
    /**
     * 换行、制表符正则表达式
     */
    public static final String JSON_LINE_SEPARATOR_REGEX="(?<![\\\\])([\r\\n\t]+)";
    
    /**
     * 序列化为字符串
     * @param obj
     * @param prettyFormat
     * @return
     * @throws JsonProcessingException 
     */
    public static final String toString(Object obj,Boolean prettyFormat) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String str=null;
        if(prettyFormat) {
            str=mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
        }else {
            str=mapper.writeValueAsString(obj);
        }
        return str;
    }
 
    

    

    
    
    
    /**
     * 反序列化
     * @param clazz
     * @param jsonString
     * @return
     * @throws Exception  
     */
    public static <T> T parseObject(Class<T> clazz,String jsonString) throws Exception {
        if(StringUtils.isEmpty(jsonString)) {
            return null;
        }
        jsonString=jsonString.replaceAll(JSON_LINE_SEPARATOR_REGEX, "");
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(jsonString, clazz);
    }
    public static <T> T parse(Class<T> clazz,String jsonString) {
        try {
            return parseObject(clazz, jsonString);
        } catch (Exception e) {
            logger.error("反序列化为Json结构异常", e);
        }
        return null;
    }
    
    public static <T> T parseObject(TypeReference<T> typeRef,String jsonString) throws Exception {
        if(StringUtils.isEmpty(jsonString)) {
            return null;
        }
        jsonString=jsonString.replaceAll(JSON_LINE_SEPARATOR_REGEX, "");
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(jsonString, typeRef);
    }
}
